<template>
  <view>
    <view class="van_top">
      <van-nav-bar title="确认订单" fixed left-arrow @click-left="onClickLeft" />
    </view>
    <view class="content" :style="{ paddingBottom: (safeAreaBottom + 50) + 'px' }">
      <view class="safe-area" :style="{ height: (statusBarHeight + 46) + 'px' }" style="width: 100%;"></view>
      <view class="inner">
        <view class="address" @click="checkAddress">
          <van-icon name="location-o" size="20px" />
          <view class="right">
            <view class="top van-ellipsis">
              {{ addressObj.region || '' }} {{ addressObj.address || "请选择收货地址" }}
            </view>
            <view class="bottom" v-if="addressObj != null">
              {{ addressObj.receiverName }} {{ addressObj.receiverPhone }}
            </view>
          </view>
          <van-icon name="arrow" size="20px" style="margin-left: auto;" />
        </view>
        <view class="shop">
          <view class="item" v-for="(item, index) in allOrderList" :key="item.id">
            <view class="pic">
              <image :src="item.images" mode="aspectFill"></image>
            </view>
            <view class="info">
              <view class="title van-ellipsis	">
                {{ item.name }}
              </view>
              <view class="sub_title" v-if="item.type == '0'">
                配送规格：{{ item.deliveryNorms }}{{ item.unitName }} * {{ item.count }}
              </view>
              <view class="sub_title" v-if="item.type == '1'">
                配送规格：{{ item.deliveryNorms }}KG * {{ item.count }}
              </view>
              <view class="sub_title">
                单价：￥{{ item.normsPrice | parseMoney }}
              </view>
            </view>
            <view class="price">
              <PriceFont color="#FF4F30" bigSize="40rpx" smallSize="40rpx" :price="item.total" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="bottomFix" :style="{ paddingBottom: safeAreaBottom + 'px' }">
      <!-- 			<view class="btn" v-if="type != '1'">申请售后</view>
			<view class="btn" v-if="type == '3'">查看物流</view>
			<view class="btn red" v-if="type == '3'">确认收货</view>
			<view class="btn red" v-if="type == '4'">再次购买</view> -->
      <view class="left">
        <text style="font-weight: 400;font-size: 28rpx;color: #808080;margin-right: 8rpx;">共{{ totalCount }}件</text>
        <text style="font-weight: 500;font-size: 28rpx;color: #333333;">合计：</text>
        <text style="font-weight: bold;font-size: 40rpx;color: #FF4F30;margin-right: 24rpx;">￥{{ totalAmount | parseMoney
        }}</text>
      </view>
      <view class="btn red" style="background-color: #FF1642;color: #fff;" @click="getCode">立即支付</view>

    </view>
    <view class="area">
      <van-popup :show="show" position="bottom" round custom-style="height: 80%;"
        :close-on-click-overlay="addressList.length == 0" @close="() => show = false"
        :closeable="addressList.length == 0">
        <view class="address_list" v-if="addressList.length > 0">
          <!-- <van-radio-group :value="radio" @change="onChange"> -->
          <view class="address_item" v-for="(item, index) in addressList" :key="item.id">
            <!-- <view class="address_check">
				        <van-radio v-model="item.id" :name="item.id"></van-radio>
				      </view> -->
            <view class="address_info" @click="onCheck(index)">
              <view class="address_address">{{ item.region }}{{ item.address }}<text class="moren"
                  v-if="item.isDefault == '0'">默认</text>
              </view>
              <view class="address_name">{{ item.receiverName }}</view>
              <view class="address_phone">{{ item.receiverPhone }}</view>
            </view>
            <view class="address_edit">
              <van-icon name="edit" size="20" @click="goEditAddress(item.id)" />
            </view>
          </view>
          <!-- </van-radio-group> -->
        </view>
        <view class="address_add_box" v-if="addressList.length > 0">
          <view class="address_add" @click="goAddAddress">
            <van-icon name="plus" size="20" />
            <text>新增收货地址</text>
          </view>
        </view>
        <view class="noAddress" v-if="addressList.length === 0">
          <view style="margin-bottom: 48rpx;">暂无收货地址</view>
          <button class="submit-btn" type="info" @click="goAddAddress">
            去新增收货地址<van-icon name="arrow" />
          </button>
        </view>
      </van-popup>
    </view>
  </view>
</template>

<script>
let safeAreaBottom = uni.getSystemInfoSync().safeAreaInsets.bottom;
import { reqCarToOrder, reqCreateOrder, reqOpenId } from "@/apis/order.js"
import { reqDeleteCartGoods } from '@/apis/rexiaogoods.js'
import app from '@/App.vue';
import { reqAddressList } from '@/apis/user'
export default {
  name: "OrderDetail",
  data() {
    return {
      statusBarHeight: app.globalData.statusBarHeight,
      safeAreaBottom: safeAreaBottom,
      allOrderList: [],
      idStr: '',
      idList: [],
      addressObj: { receiverName: '', receiverPhone: '', address: '', region: '' },
      totalAmount: 0,
      totalCount: 3,
      openid: '',
      show: false,
      addressList: []
    };
  },
  onLoad(params) {
    if (params.idList != '') {
      this.idStr = params.idList;
      this.idList = this.idStr.split(',');
      this.getOrderList();
    }
  },
  async onShow() {
    await this.getAddressList();
    if (this.addressList.length === 0) {
      this.addressObj = null;
    }
  },
  methods: {
    onClickLeft() {
      uni.navigateBack();
    },
    async getOrderList() {
      let res = await reqCarToOrder({ idList: this.idStr });
      if (res.code === 200) {
        this.addressObj = res.data.address;
        console.log('this.addressObj', this.addressObj);
        this.allOrderList = res.data.list;
        this.totalAmount = res.data.totalAmount;
        this.totalCount = res.data.totalCount;
      }
    },
    async getAddressList() {
      let res = await reqAddressList();
      if (res.code === 200) {
        this.addressList = res.data;
      }
    },
    async checkAddress() {
      this.show = true;
    },
    goAddAddress() {
      uni.navigateTo({ url: '/packageA/pages/addAddress/addAddress' })
    },
    goEditAddress(id) {
      uni.navigateTo({ url: `/packageA/pages/editAddress/editAddress?id=${id}` })
    },
    onCheck(index) {
      this.addressObj = this.addressList[index],
        this.show = false;
    },
    async getCreateOrder() {
      let { idList, openid } = this;
      let { address: receiverAddress, receiverName, receiverPhone, region: receiverRegion } = this.addressObj;

      try {
        let res = await reqCreateOrder({
          idList, openid, orderType: 0, payType: 0, receiverAddress, receiverRegion, receiverName, receiverPhone,
          sourceType: 0
        });
        console.log('11111');
        if (res.code === 200) {
          let data = res.data;
          let res1 = await reqDeleteCartGoods({ idList: this.idList });
          if (res1.code === 200) {
            this.$store.dispatch('car/addToCar', res1.data)
            this.$store.dispatch('car/addActivedList', [])
          }
          wx.requestPayment({
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.packageInfo,
            signType: data.signType,
            paySign: data.paySign,
            success: (suc) => {
              // 直接支付
              uni.navigateBack();
            },
            fail: (error) => {
              // 取消支付
              let pages = getCurrentPages();
              let prevPage = pages[pages.length - 1]; //当前页面路由

              if (prevPage.route === 'packageA/pages/enterOrder/enterOrder') {
                uni.redirectTo({ url: `/packageA/pages/orderList/orderList?index=0` })
              } else {
                uni.navigateTo({ url: `/packageA/pages/orderList/orderList?index=0` })
              }
            },
            complete: (com) => {
              console.log('支付拉起结束', com);
            }
          })
        }
      } catch (error) {
        console.log('error', error);
        uni.showModal({
          title: '提示',
          content: error.message,
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },
    getCode() {
      if (!this.addressObj) {
        uni.utils.toast("请选择收货地址");
        return;
      }
      uni.showLoading({ title: '加载中' })
      uni.login({
        success: async (res) => {
          if (res.errMsg == "login:ok") {
            let code = res.code;
            uni.hideLoading();
            let r = await reqOpenId({ code });
            if (r.code === 200) {
              this.openid = r.data.openid;
              console.log('this.openid', this.openid);
              this.getCreateOrder();
            }
          } else {
            uni.utils.toast('系统异常，请联系管理员')
          }
        }
      })
    }

  },
}
</script>
<style>
page {
  background: #f5f5f5;
}
</style>

<style lang="scss" scoped>
.content {
  .inner {
    padding: 24rpx;
    box-sizing: border-box;

    .address {
      padding: 24rpx 30rpx;
      background-color: #fff;
      border-radius: 24rpx;
      display: flex;
      margin-bottom: 24rpx;

      .right {
        margin-left: 18rpx;
        width: 83%;

        .top {
          font-size: 32rpx;
          color: #333333;
        }

        .bottom {
          margin-top: 20rpx;
          font-size: 28rpx;
          color: #808080;
        }
      }
    }

    .shop {
      padding: 24rpx;
      background-color: #fff;
      border-radius: 24rpx;
      margin-bottom: 24rpx;

      .item {
        display: flex;
        margin-bottom: 20rpx;

        .pic {
          width: 148rpx;
          height: 148rpx;
          margin-right: 16rpx;

          image {
            width: 100%;
            height: 100%;
          }
        }

        .info {
          width: 302rpx;

          .title {
            width: 100%;
            font-weight: 500;
            font-size: 28rpx;
            color: #333333;
            margin-bottom: 16rpx;
          }

          .sub_title {
            font-weight: 500;
            font-size: 24rpx;
            color: #808080;
            margin-bottom: 16rpx;
          }
        }

        .price {
          flex: 1;
          text-align: right;
          font-weight: 500;
          font-size: 40rpx;
          color: #333333;
          align-self: flex-start;
        }

      }

      .total {
        display: flex;
        width: 100%;
        height: 64rpx;
        border-top: 1px solid #f5f5f5;
        justify-content: space-between;
        align-items: center;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
      }
    }
  }
}

.bottomFix {
  position: fixed;
  width: 750rpx;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  justify-content: flex-end;
  bottom: 0;
  padding-right: 24rpx;
  align-items: center;

  .btn {
    margin-right: 24rpx;
    width: 168rpx;
    height: 64rpx;
    border-radius: 38rpx;
    border: 2rpx solid #DDDDDD;
    font-weight: 400;
    font-size: 28rpx;
    color: #333333;
    line-height: 64rpx;
    text-align: center;

    &.red {
      color: #FF1642;
      border: 2rpx solid #FF1642;
    }
  }
}


.address_list {
  background-color: #fff;
  padding: 24rpx 40rpx 100rpx 40rpx;
  position: relative;

  .address_item {
    height: 146rpx;
    width: 100%;
    border-bottom: 1px solid #EEEEEE;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .address_check {
      width: 10%;
      text-align: center;
      padding-left: 5%;
    }

    .address_edit {
      width: 10%;
    }

    .address_info {
      flex: 1;
      display: flex;
      flex-wrap: wrap;
      padding-top: 24rpx;

      .address_address {
        width: 100%;
        font-weight: 500;
        font-size: 28rpx;
        color: #333333;
        line-height: 33rpx;
        text-align: left;
        margin-bottom: 24rpx;

        .moren {
          width: 76rpx;
          height: 36rpx;
          line-height: 36rpx;
          text-align: center;
          border-radius: 6rpx 6rpx 6rpx 6rpx;
          border: 2rpx solid #FF1642;
          font-weight: 400;
          font-size: 24rpx;
          color: #FF1642;
          margin-left: 24rpx;
          display: inline-block;
          // padding: 4rpx;
        }
      }

      .address_name {
        width: 40%;
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
        line-height: 28rpx;
        text-align: left;
        // margin-right: 96rpx;
      }

      .address_phone {
        width: 50%;
        font-weight: 400;
        font-size: 24rpx;
        color: #999999;
        line-height: 28rpx;
        text-align: left;
      }
    }
  }


}

.address_add_box {

  position: fixed;
  bottom: 0;
  left: 0;
  height: 110rpx;
  width: 100%;
  background-color: #fff;
  margin: 0 auto;
  text-align: center;
  padding-left: 24rpx;
  padding-bottom: 20rpx;

  .address_add {
    width: 702rpx;
    height: 76rpx;
    background: #FF1642;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    line-height: 76rpx;
    text-align: center;
    font-weight: 500;
    font-size: 32rpx;
    color: #FFFFFF;
  }
}

.noAddress {
  padding-top: 216rpx;
  font-weight: 600;
  font-size: 40rpx;
  color: #333333;
  text-align: center;

  .submit-btn {
    width: 478rpx;
    height: 76rpx;
    background: #FF1642;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    font-weight: 500;
    font-size: 32rpx;
    color: #FFFFFF;
    line-height: 76rpx;
    letter-spacing: 2rpx;
  }
}
</style>